package com.changgou.user.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.order.pojo.Task;
import com.changgou.user.config.RabbitMQConfig;
import com.changgou.user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author: HuangFu
 * @Date: 2020/2/18 10:42
 * @Description: 用户积分监听
 */
@Component
public class UserPointsListener {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = RabbitMQConfig.CG_BUYING_ADDPOINT)
    public void receiveAddPointMessage(String message){
        Task task = JSON.parseObject(message, Task.class);
        //校验数据合法性
        if(task == null || StringUtils.isEmpty(task.getRequestBody())){
            return;
        }
        //校验Redis中是否有任务
        String str = (String) redisTemplate.boundValueOps(task.getId()).get();
        if (StringUtils.isNotEmpty(str)){
            return;
        }

        //更新用户积分
        int result = userService.updateUserPoints(task);
        if(result == 0){
            return;
        }

        //发送积分消息处理成功
        rabbitTemplate.convertAndSend(RabbitMQConfig.EX_BUYING_ADDPOINTUSER,RabbitMQConfig.CG_BUYING_FINISHADDPOINT_KEY,message);
        System.out.println("用户服务向完成添加积分队列发送了一条消息");
    }

}
